import dayjs from 'dayjs'
import { WX_OCR_SERVICEID } from '@/config/index.js'

export const isExpired = (dateTime)=>{
	return !dayjs().isBefore(dayjs(reformatDatetime(dateTime)))
};

/**
 * 格式化开始时间
 */
export const formatBeginTime = (time) => {
	const now = dayjs()
	const begin = dayjs(reformatDatetime(time))
	const diffDay = now.diff(begin, 'day')

	if (diffDay > 0) {
		if (diffDay > 7) {
			return time
		}
		return `${diffDay}天前`
	} else {
		const diffHour = now.diff(begin, 'hour')
		if (diffHour > 0) {
			return `${diffHour}小时前`
		} else {
			const diffMin = now.diff(begin, 'minute')
			return diffMin > 0 ? `${diffMin}分钟前` : '刚刚'
		}
	}
}

/**
 * 格式化结束剩余时间
 */
export const formatEndTime = (time) => {
	const now = dayjs()
	const end = dayjs(reformatDatetime(time))
	const diffDay = end.diff(now, 'day')
	let diffHour = end.diff(now, 'hour')
	let diffMin = end.diff(now, 'minute')
	let rest = ''
	if (diffDay > 0) {
		rest += `${diffDay}天`
		diffHour = diffDay % 24
	}
	if (diffHour > 0) {
		rest += `${diffHour}小时`
		diffMin = diffMin % 60
	}
	if (diffMin > 0) {
		rest += `${diffMin}分钟`
	}
	return rest
}

/****
*计算高度 屏幕高度 - h(其他容器高度) - 导航栏
*多用于计算滚动scroll-view标签高度
**/ 
export function mathHeight(h,type){
	let systemInfo = uni.getSystemInfoSync()
	var res =  ((systemInfo.windowHeight- h - systemInfo.statusBarHeight))
	if (type!=false){
		res = res + 'px'
	}
	return res
}

/**
 * 倒计时剩余天数、小时、分钟、秒
 */
export const endTimeDetail = (time) => {
	const now = dayjs()
	const end = dayjs(reformatDatetime(time))
	const day = end.diff(now, 'day')
	let hour = end.diff(now, 'hour')
	let min = end.diff(now, 'minute')
	let sec = end.diff(now, 'second')
	if (day > 0) {
		hour = day % 24
	}
	if (hour > 0) {
		min = min % 60
	}
	if (min > 0) {
		sec = min % 60
	}
	return {
		day,
		hour,
		min,
		sec
	}
}

/**
 * 比较2个时间的间隔天数
 */
export const diffDay = (time1, time2) => {
	if (time1 && time2) {
		const diff = dayjs(time1).diff(dayjs(time2), 'day')
		return Math.abs(diff)
	}
}

/***
*小程序弹窗
**/ 
export function modelShowToast (params,success,fial){
	let obj = {
		confirmColor:'#00AEFF',
		cancelColor:'#333333',
		cancelText:'取消',
		confirmText:'确定'
	}
	obj = Object.assign(obj,params)
	uni.showModal({
		...obj,
		success: function (res) {
			if (res.confirm) {
				if(success){
					success()
				}
			} else if (res.cancel) {
				if(fial){
					fial()
				}
			}
		}
	});

}

export function modelShowToastAsync(params){
	return new Promise(resolve=>{
		modelShowToast(params,()=>resolve(true),()=>resolve(false))
	});
}

// 判断邮件是否正确
export function validateEmail(email) {
    // 定义电子邮件地址的正则表达式模式
    var pattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    
    if (pattern.test(email)) {
        return true; // 如果符合规则返回true
    } else {
        return false; // 不符合规则返回false
    }
}
export function checkPhoneNumber(phone) {
    var regExp = /^1[3456789]\d{9}$/; // 中国大陆手机号的正则表达式
    
    if (regExp.test(phone)) {
        return true; // 符合手机号格式要求
    } else {
        return false; // 不符合手机号格式要求
    }
}

// 格式化金额，默认为人民币
export function moneyFormater(amount) {
	return amount.toLocaleString('zh-CN', {
		style: 'currency',
		currency: 'CNY',
		minimumSignificantDigits: 2, // 最少保留2位小数
		maximumSignificantDigits: 2, // 最多保留2位小数
	})
}
// 判断数后面小数位是否小于等于两位
export function judegDit(num){
	var reg= /^(-?\d+)(\.\d{1,2})?$/
	if(reg.test(num+''))
	{
		return true
	}else{
		return false
	}
}
// 格式化小数，保留指定位数
export function numberFormat(value = 0, decimal = 2) {
	let exp = /^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/;//判断是否是数字格式
	if(!exp.test(value)){
		uni.showToast({
			icon:'none',
			title:`请输入正确的数字格式`
		})
		value =  0	
	}
	return value != undefined && value != null && (+value).toFixed(decimal)
}

// 向下保留指定位数，非四舍五入
export function floorNumber(value, decimal = 2) {
	// 多保留一个小数位，再截取掉
	const val = value.toFixed(decimal + 1).padEnd(3, '0')
	// console.log('向下去小数', value, decimal, val)
	return val.substring(0, val.length - 1)
}

// 是否视频文件
export function isVideoFile(path) {
	const videoExtensions = /\.(mp4|flv|avi|mov|wmv|mkv)$/i
	return videoExtensions.test(path)
}

// 时间格式从yyyy.MM.dd HH:mm:ss 格式化为yyyy-MM-dd HH:mm:ss
export function reformatDatetime (date) {
	const reg = new RegExp(/\./g)
	return date && date.replace(reg, '-') || ''
}

export function formatDatetime (datetime,formatStr){
	const newDateTime = reformatDatetime(datetime);
	const result = dayjs(newDateTime).format(formatStr)
	return result==='Invalid Date'?'':result
}

/**
 * 处理富文本里的图片宽度自适应
 * 1.去掉img标签里的style、width、height属性
 * 2.img标签添加style属性：max-width:100%;height:auto
 * 3.修改所有style里的width属性为max-width:100%
 * 4.去掉&lt;br/&gt;标签
 * @param html
 * @returns {void|string|*}
 */
export function formatRichText(html){
  let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
	  match = match.replace(/style=""/, '').replace(/style=''/, '')
      match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
      match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
      match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
      return match;
  });
  newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
      match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
      return match;
  });
  newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:10px 0;"');
  return newContent;
}

/**
 * 小程序码参数解析
 * @param {String} scene
 * @returns {Object}
 */
export function parseScene(scene) {
	const obj = {}
	if (!scene) {
		return obj
	} else {
		scene = decodeURIComponent(scene)
		const arr = scene.split('&') || []
		if (arr.length) {
			arr.forEach(val => {
				const keyValue = val.split('=')
				if (keyValue.length > 1) {
					obj[keyValue[0]] = keyValue[1]
				}
			})
			return obj
		} else {
			const keyValue = scene.split('=')
			if (keyValue.length > 1) {
				obj[keyValue[0]] = keyValue[1]
			}
			return obj
		}
	}
}

// 防抖
export function debounce (fn, delay = 300) {
	let timer = null
	return function (...args) {
		clearTimeout(timer)
		timer = setTimeout(() => {
			fn.call(this, ...args)
		}, delay)
	}
}

// 节流
export function throttle (fn, delay = 300) {
	let timer = null
	return function (...args) {
		if (timer == null) {
			timer = setTimeout(() => {
				fn.call(this, ...args)
				clearTimeout(timer)
				timer = null
			}, delay)
		}
	}
}

/**
 * 格式化金额输入
 * 最大不能超过99999999，保留两位小数
 */
export function formatMoneyInput (value, max=99999999) {
	console.log('输入', value)
	let result
	if (+value > max) {
		result = `${max}.00`
	} else if (+value < 0) {
		result = '0.00'
	} else {
		result = numberFormat(value)
	}
	console.log('格式化后：', result)
	return result
}

export function toRouterParamsStr(params, isFirstParams = true) {
  if (!params) return "";
  let paramsStr = Object.keys(params)
    .filter((key) => !(params[key] === undefined || params[key] === null))
    .map((key) => `${key}=${params[key]}`)
    .join("&");

  return isFirstParams && paramsStr ? `?${paramsStr}` : paramsStr;
}

export const ocrImage = async (imgUrl,ocrType)=>{
	return await wx.serviceMarket.invokeService({
		service: WX_OCR_SERVICEID,
		api: 'OcrAllInOne',
		data: {
			img_url: imgUrl,
			data_type: 3, // 1：二进制；2：base64字符串；3：图片url
			ocr_type: ocrType // 1：身份证；2：银行卡；3：行驶证；4：驾驶证；7：营业执照；8：通用OCR ; 10: 车牌识别
		},
	});
}